package de.tapps.brainstorming;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ListActivity;
import android.os.AsyncTask;
import android.widget.ArrayAdapter;
/**
 * Reads the Answers to a specific topic (an id) and shows them in a List
 * 
 * @author Timo
 * Decrypted - ok
 */
public class AnswerList extends AsyncTask <String, Integer, String> {
	private int id;
	private MainActivity activity = new MainActivity();
	private Crypter crypter;
	public AnswerList(MainActivity act,int pid) {
		id = pid;
		activity = act;
		crypter = new Crypter(activity);

	}

	@Override
	protected String doInBackground(String... arg0) {
		new Thread(new Runnable() {
			public void run() {
				URL url = null;
				ArrayList<String> listEintraege = new ArrayList<String>();
				ArrayList<Integer> IDs = new ArrayList<Integer>();

				try {
					url = new URL(
							"http://t-apps-online.de/BrainStorming/getAnswerList.php?id="
									+ id);
					String readLine = null;
					BufferedReader buffReader = new BufferedReader(
							new InputStreamReader(url.openStream()));
					int counter = 0;
					while ((readLine = buffReader.readLine()) != null) {
						if (counter % 2 == 0){
					listEintraege.add(crypter.decrypt(readLine));
						}
						else {
							IDs.add(Integer.valueOf(readLine));
						}
						counter++;
					}
				} catch (MalformedURLException me) {
					me.printStackTrace();
				} catch (IOException ioe) {
					ioe.printStackTrace();
				}
				activity.answerlist = listEintraege.toArray(new String[listEintraege
						.size()]);
				activity.answerIDs = IDs.toArray(new Integer[IDs.size()]);

				activity.runOnUiThread(new Runnable() {
					public void run() {
						ArrayAdapter<String> adapter = new ArrayAdapter<String>(
								activity, R.layout.custom_list_answers,
								activity.answerlist);
						activity.setListAdapter(adapter);
					}
				});
			}
		}).start();
		return null;
	}
}